package cn.com.yusys.dtm.check.timerTask;

import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import cn.com.yusys.dtm.check.util.CommandUtils;
import cn.com.yusys.dtm.check.util.OSUtils;

/**
 * @author 杨得朝
 * @since 1.1.1
 */
public class LinuxProcessLoggerTask implements SchedulingConfigurer {

	private final static Logger log = LoggerFactory.getLogger(LinuxProcessLoggerTask.class);
	/**
	 * dbpool日志开关
	 */
	@Value(value = "${linux.log.process.enable:true}")
	private Boolean isSwitch;
	/**
	 * jvm周期cron表达式
	 */
	@Value(value = "${linux.log.process.collectFreq:0/5 * * * * ?}")
	private String cron;

	@Override
	public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
		log.debug("LinuxProcessLoggerTask开关isSwitch=" + isSwitch);
		if (isSwitch) {
			scheduledTaskRegistrar.addTriggerTask(() -> {
				try {
					writeLog();
				} catch (Exception e) {
					log.error("writeLog", e);
				}
			},
					// set trigger
					triggerContext -> {
						// Initialize scheduled task cycle

						if (StringUtils.isEmpty(cron)) {
							cron = getCron();
						}
						CronTrigger trigger = new CronTrigger(cron);
						return trigger.nextExecutionTime(triggerContext);
					});
		}

	}

	/**
	 * 获取周期表达式
	 */
	protected String getCron() {
		return cron;
	}

	public void writeLog() {
		try {
			//String path = System.getProperty("user.dir");
			String logFilePath = "./process-log/process.log";
			String dateCommand = "date \"+%Y-%m-%d %H:%M:%S\" >>" + logFilePath;
			String procCommand = "top -b -n1 >> " + logFilePath;
			String procTotalCommand = " ps auxw | wc -l >> " + logFilePath;
			String[] cmdBegin = new String[] { "sh", "-c", "echo '-------------------------------begin-----------------------------------------' >> "+logFilePath  };
			String[] cmdEnd = new String[] { "sh", "-c", "echo '-------------------------------end-----------------------------------------' >> "+logFilePath  };

			String[] cmdDate = new String[] { "sh", "-c", dateCommand };
			String[] cmdProc = new String[] { "sh", "-c", procCommand };
			String[] cmdProcTotal = new String[] { "sh", "-c", procTotalCommand };

			//String cpuUsage = OSUtils.cpuUsage() +"%";
			String cpuUsage2 = OSUtils.getCpuUsage() +"%";

			String memoryUsage = OSUtils.memoryUsage() +"%";
			log.info("begin collect process info");
			File file1 = new File("./process-log");
			if (!file1.exists()) {
				file1.mkdirs();// 创建目录
			}
			CommandUtils.run(cmdBegin);

			CommandUtils.run(new String[] { "sh", "-c", "echo '当前时间为' >> "+logFilePath });
			CommandUtils.run(cmdDate);

			CommandUtils.run(new String[] { "sh", "-c", "echo 'CPU使用率:' >> "+logFilePath });
			CommandUtils.run(new String[] { "sh", "-c", "echo "+cpuUsage2+" >> "+logFilePath });
			
			CommandUtils.run(new String[] { "sh", "-c", "echo '内存使用率:' >> "+logFilePath });
			CommandUtils.run(new String[] { "sh", "-c", "echo "+memoryUsage+" >> "+logFilePath });
			
			CommandUtils.run(new String[] { "sh", "-c", "echo '活跃进程数量为:' >> "+logFilePath });
			CommandUtils.run(cmdProcTotal);

			
			CommandUtils.run(new String[] { "sh", "-c", "echo '进程信息为:' >> "+logFilePath });
			CommandUtils.run(cmdProc);
			
			CommandUtils.run(cmdEnd);


		} catch (IOException e) {
			log.error("异常", e);
		}
		log.info("collect process info end");
	}
}
